using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TrackSystem.IO.Data;
using TrackSystem.IO.Models;

namespace TrackSystem.IO.Protocol
{

    /// <summary>
    /// USBL通信协议 "$PTSAG,#<usbl_code1>,<usbl_time1>,<usbl_dd1>,<usbl_mm1>,<usbl_yy1>,00,<usbl_lat1>,N,<usbl_lon1>,E,..."
    /// 0--时间;
    /// 1--日期--日;
    /// 2--日期--月;
    /// 3--日期--年;
    /// 4--目标1;
    /// 5--目标1 纬度 N-正,S-负;
    /// 6--目标1 经度 E-正,W-负;
    /// 7--目标2;
    /// 8--目标2 纬度 N-正,S-负;
    /// 9--目标2 经度 E-正,W-负;
    /// 10--目标3;
    /// 11--目标3 纬度 N-正,S-负;
    /// 12--目标3 经度 E-正,W-负;
    /// 13--最大支持10个目标;
    /// </summary>
    /// 




    public class Ship2USBLProtocol : ProtocolBase
    {
        private int startTicks;
        private bool bSendR;
        private int BeckIndex;
        private long lastDtTicks;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="name"></param>
        public Ship2USBLProtocol(string name)
            : base()
        {
            NeedInit = false;
            Name = name;
            bSendR = false;
            BeckIndex = 0;
            lastDtTicks = Environment.TickCount;   //DateTime.Now.Ticks;
        }

        /// <summary>
        /// 生成读取寄存器的通讯帧
        /// </summary>
        /// <returns></returns>
        public override byte[] GenerateReadFrame(out int NeedRecvLen)
        {
            startTicks = Environment.TickCount;
            if (bSendR)
            {
                Fail_R++;
                // 失败超过10次，成功次数清零
                if (Fail_R >= 10)
                {
                    Succ_R = 0;
                }
            }
            bSendR = true;
            NeedRecvLen = 1024;
            return null;
        }


        /// <summary>
        /// 根据收到的内容进行处理
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public bool ProcessReadFrame_bak(byte[] buffer)
        {
            var DataFactory = RegFactory.Instance;
            Lapse = Environment.TickCount - startTicks;
            try
            {
                string frame = Encoding.UTF8.GetString(buffer);
                string[] ar_line = frame.Split('$');
                try
                {
                    for (int i = 0; i < ar_line.Length; i++)
                    {
                        string[] ar_str = ar_line[i].Split(',');
                        Rx_r = buffer;  // 用于显示的接收帧内容
                        int strLen = ar_str.Length;

                        if (strLen < 6)   // 数据长度小于6
                        {
                            continue;
                        }
                        //$PTSAG,#<usbl_code1>,<usbl_time1>,<usbl_dd1>,<usbl_mm1>,<usbl_yy1>,00,<usbl_lat1>,N,<usbl_lon1>,E,01,<usbl_lat1>,N,<usbl_lon1>,E,
                        //$PTSAG,#<usbl_code1>,<usbl_time1>,<usbl_dd1>,<usbl_mm1>,<usbl_yy1>,01,<usbl_lat1>,N,<usbl_lon1>,E,01,<usbl_lat1>,N,<usbl_lon1>,E,
                        if (ar_str[0] == "PTSAG")
                        {
                            bSendR = false;
                            double d1 = double.Parse(ar_str[2]); // 时间
                            double d2 = double.Parse(ar_str[3]); // 日
                            double d3 = double.Parse(ar_str[4]); // 月
                            double d4 = double.Parse(ar_str[5]); // 年
                            DataFactory.SetVal(RegNameList[0], d1);
                            DataFactory.SetVal(RegNameList[1], d2);
                            DataFactory.SetVal(RegNameList[2], d3);
                            DataFactory.SetVal(RegNameList[3], d4);
                            if (strLen >= 11)
                            { //目标
                                int d5 = int.Parse(ar_str[6]); // 目标编号
                                double d6 = double.Parse(ar_str[7]); // 目标纬度
                                int d6_temp = (int)(d6 / 100); // 提取度
                                double d6_temp2 = (d6 - d6_temp * 100) / 60;// 分转化为度
                                d6 = Math.Round(d6_temp + d6_temp2, 6);
                                if (ar_str[8] == "S")
                                {
                                    d6 = -1 * d6;
                                }
                                double d7 = double.Parse(ar_str[9]); // 目标经度
                                int d7_temp = (int)(d7 / 100); // 提取度
                                double d7_temp2 = (d7 - d7_temp * 100) / 60;// 分转化为度
                                d7 = Math.Round(d7_temp + d7_temp2, 6);
                                if (ar_str[10] == "W")
                                {
                                    d7 = -1 * d7;
                                }
                                if (d5 == 0)
                                {
                                    DataFactory.SetVal(RegNameList[4], d5);
                                    DataFactory.SetVal(RegNameList[5], d6);
                                    DataFactory.SetVal(RegNameList[6], d7);
                                }
                                else if (d5 == 1)
                                {
                                    DataFactory.SetVal(RegNameList[7], d5);
                                    DataFactory.SetVal(RegNameList[8], d6);
                                    DataFactory.SetVal(RegNameList[9], d7);
                                }
                                else if (d5 == 2)
                                {
                                    DataFactory.SetVal(RegNameList[10], d5);
                                    DataFactory.SetVal(RegNameList[11], d6);
                                    DataFactory.SetVal(RegNameList[12], d7);
                                }
                                else if (d5 == 3)
                                {
                                    DataFactory.SetVal(RegNameList[13], d5);
                                    DataFactory.SetVal(RegNameList[14], d6);
                                    DataFactory.SetVal(RegNameList[15], d7);
                                }
                                else if (d5 == 4)
                                {
                                    DataFactory.SetVal(RegNameList[16], d5);
                                    DataFactory.SetVal(RegNameList[17], d6);
                                    DataFactory.SetVal(RegNameList[18], d7);
                                }
                                else if (d5 == 5)
                                {
                                    DataFactory.SetVal(RegNameList[19], d5);
                                    DataFactory.SetVal(RegNameList[20], d6);
                                    DataFactory.SetVal(RegNameList[21], d7);
                                }
                                else if (d5 == 6)
                                {
                                    DataFactory.SetVal(RegNameList[22], d5);
                                    DataFactory.SetVal(RegNameList[23], d6);
                                    DataFactory.SetVal(RegNameList[24], d7);
                                }
                                else if (d5 == 7)
                                {
                                    DataFactory.SetVal(RegNameList[25], d5);
                                    DataFactory.SetVal(RegNameList[26], d6);
                                    DataFactory.SetVal(RegNameList[27], d7);
                                }
                                else if (d5 == 8)
                                {
                                    DataFactory.SetVal(RegNameList[28], d5);
                                    DataFactory.SetVal(RegNameList[29], d6);
                                    DataFactory.SetVal(RegNameList[30], d7);
                                }
                                else if (d5 == 9)
                                {
                                    DataFactory.SetVal(RegNameList[31], d5);
                                    DataFactory.SetVal(RegNameList[32], d6);
                                    DataFactory.SetVal(RegNameList[33], d7);
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    return false;
                }
                if (!bSendR)
                    Succ_R++;
                // 失败次数清零
                if (Succ_R > 30 && Fail_R > 0)
                {
                    Fail_R = 0;
                }
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }


        /// <summary>
        /// 根据收到的内容进行处理
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public override bool ProcessReadFrame(byte[] buffer)
        {
            var DataFactory = RegFactory.Instance;

            Lapse = Environment.TickCount - startTicks;
            try
            {
                BeckIndex = 1 - BeckIndex;  // 当前信标编号
                string frame = Encoding.UTF8.GetString(buffer);
                string[] ar_line = frame.Split('$');
                try
                {
                    // 对每条数据帧进行解析
                    for (int i = 0; i < ar_line.Length; i++)
                    {
                        string[] ar_str = ar_line[i].Split(',');
                        Rx_r = buffer;  // 用于显示的接收帧内容
                        int strLen = ar_str.Length;

                        if (strLen < 6)   // 数据长度小于6
                        {
                            continue;
                        }

                        // --------------------------  信标深度、距离等信息-------------------------------------------------
                        // $PTSAX, #10367, 102720.815, 02, 05, 2023, 01, -0083, -0045, 1, -1295, 1, 0000*66
                        //if (ar_str[0] == "PTSAX")
                        //{
                        //    if (strLen > 10)
                        //    {
                        //        int d0 = int.Parse(ar_str[1].Substring(1));
                        //        double d1 = double.Parse(ar_str[7]);
                        //        double d2 = double.Parse(ar_str[8]);
                        //        double d3 = double.Parse(ar_str[10]);
                        //        BeckIndex = d0 % 2;
                        //        DataFactory.SetVal(RegNameList[7 + 6 * BeckIndex], d1);
                        //        DataFactory.SetVal(RegNameList[8 + 6 * BeckIndex], d2);
                        //        DataFactory.SetVal(RegNameList[9 + 6 * BeckIndex], d3);
                        //    }
                        //}

                        // --------------------------  信标位置等信息-------------------------------------------------
                        //$PTSAG,#<usbl_code1>,<usbl_time1>,<usbl_dd1>,<usbl_mm1>,<usbl_yy1>,00,<usbl_lat1>,N,<usbl_lon1>,E,01,<usbl_lat1>,N,<usbl_lon1>,E,1,<Distance>
                        //$PTSAG,#<usbl_code1>,<usbl_time1>,<usbl_dd1>,<usbl_mm1>,<usbl_yy1>,01,<usbl_lat1>,N,<usbl_lon1>,E,01,<usbl_lat1>,N,<usbl_lon1>,E,1,<Distance>
                        if (ar_str[0] == "PTSAG")
                        {
                            bSendR = false;
                            double d1 = double.Parse(ar_str[2]); // 时间
                            double d2 = double.Parse(ar_str[3]); // 日
                            double d3 = double.Parse(ar_str[4]); // 月
                            double d4 = double.Parse(ar_str[5]); // 年
                            DataFactory.SetVal(RegNameList[0], d1);
                            DataFactory.SetVal(RegNameList[1], d2);
                            DataFactory.SetVal(RegNameList[2], d3);
                            DataFactory.SetVal(RegNameList[3], d4);
                            if (strLen > 11)
                            { 
                                //目标
                                int d5 = int.Parse(ar_str[6]); // 目标编号
                                double d6 = double.Parse(ar_str[7]); // 目标纬度
                                int d6_temp = (int)(d6 / 100); // 提取度
                                double d6_temp2 = (d6 - d6_temp * 100) / 60;// 分转化为度
                                d6 = Math.Round(d6_temp + d6_temp2, 6);
                                if (ar_str[8] == "S")
                                {
                                    d6 = -1 * d6;
                                }
                                double d7 = double.Parse(ar_str[9]); // 目标经度
                                int d7_temp = (int)(d7 / 100); // 提取度
                                double d7_temp2 = (d7 - d7_temp * 100) / 60;// 分转化为度
                                d7 = Math.Round(d7_temp + d7_temp2, 6);
                                if (ar_str[10] == "W")
                                {
                                    d7 = -1 * d7;
                                }

                                // -------------------------------------
                                if (d5 != 0)
                                {
                                    // 计算本次收到数据帧和上次的时间差，超过1s则重新从0号信标开始
                                    long ms = Environment.TickCount;
                                    if ((ms - lastDtTicks) > 1000)
                                    {
                                        BeckIndex = 0;
                                    }
                                    else
                                    {
                                        if (BeckIndex < 3)
                                            BeckIndex++;
                                    }
                                    lastDtTicks = ms;

                                    //int idx = int.Parse(ar_str[1].Trim().Substring(1));
                                    //BeckIndex = idx % 2;

                                    // 经纬度
                                    DataFactory.SetVal(RegNameList[4 + 6 * BeckIndex], d6); 
                                    DataFactory.SetVal(RegNameList[5 + 6 * BeckIndex], d7);

                                    // 斜距
                                    double d8 = double.Parse(ar_str[12]);
                                    DataFactory.SetVal(RegNameList[6 + 6 * BeckIndex], d8);
                                }
                                else
                                {
                                    // 经纬度
                                    DataFactory.SetVal(RegNameList[25], d6);
                                    DataFactory.SetVal(RegNameList[26], d7);

                                    // 斜距
                                    double d8 = double.Parse(ar_str[12]);
                                    DataFactory.SetVal(RegNameList[27], d8);
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    return false;
                }

                if (!bSendR) {
                    Succ_R++;   // 成功次数加1
                    if(Succ_R >30 && Fail_R > 0)
                        Fail_R = 0;
                }
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

    }
}
